local email_tool = { email = require("resty.mail") }

-- Envía correos electrónicos en formato HTML utilizando el protocolo SMTP.
function email_tool:send(email_struct)
	local site_email  = require("utils.website_config").website_email
	local username    = site_email.username

	-- Captura fallos del cliente SMTP y los muestra en los logs. 
	local function try_ngx(fname,catch_ngx)
		ngx.log(ngx.ERR, fname.." error: ", catch_ngx)
		return false
	end

	-- Configura el cliente SMTP con los datos del servidor de correo electrónico.
	local mailer, mailer_err = self.email.new({
		host            = site_email.host,
		port            = site_email.port,
		starttls        = site_email.starttls,
		ssl             = site_email.ssl,
		username        = username,
		password        = site_email.password,
		timeout_connect = 2000,
		timeout_send    = 2000,
		timeout_read    = 2000
	})

	if mailer_err then
		return try_ngx("self.email.new", mailer_err)
	end

	-- Envía un correo electrónico desde el cliente SMTP.
	local send_ok, send_err = mailer:send({
		from    = require("utils.website_config").website_name.." <"..username..">",
		to      = { '"'..email_struct.name..'" <'..email_struct.destination..'>' },
		subject = email_struct.subject,
		html    = email_struct.message
	})

	if send_err then
		return try_ngx("mailer:send", send_err)
	end

	return true
end

return setmetatable({}, { __index = email_tool })